// import 'dart:convert';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/pages/login/automatic2_page.dart';
import 'package:hktk_app/pages/login/device_ask_page.dart';
import 'package:hktk_app/pages/select/select_exam_page.dart';
// import 'package:hktk_app/test_page/my_calendar.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
// import 'package:hktk_app/test_page/my_video.dart';
import 'package:hktk_app/util/device_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/toast_util.dart';
// import 'package:hktk_app/util/yidun_util.dart';
import 'package:http/http.dart' as http show get; // 此处
import 'package:hktk_app/routes.dart';

import 'navigotr/tab_navigator.dart';


final  observer= RouteObserver();
void main() {
  // Logger.root.level = Level.ALL; // 设置日志级别
  // Logger.root.onRecord.listen((record) {
  //   // 自定义打印全部属于flutter com.yquestion.zzwx下
  //   print('${record.level.name}: ${record.time}: ${record.message}');
  // });

  // FlutterError.onError = (details, {bool forceReport = false}) {
  //   debugPrint(details.exceptionAsString());
  //   debugPrintStack(stackTrace: details.stack);
  // };

  debugPaintSizeEnabled = true;

  // 捕获 Dart 层未处理异常
  // PlatformDispatcher.instance.onError = (error, stack) {
  //   _logError(error.toString(), stackTrace: stack);
  //   return true; // 表示已处理
  // };
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // final Fluwx fluwx = Fluwx();
  late bool _isLoading = true;
  late Map<String, dynamic>? internetResponse;


  @override
  void initState() {
    //   initState
    super.initState();




    List<Future> promiseArray = [];
    promiseArray.add(Fluwx().registerApi(
      appId: "wx044d8096de012255",
      universalLink: "https://www.yunxuebao.com/zzwxPath/",
      doOnAndroid: true,
      doOnIOS: true,
    ));

    promiseArray.add(HiCache.preInit());
    // iOS如果是首次安装，开始检测网络权限，等待权限完成
    if (Platform.isIOS) {
      bool wifiPermissions = false;
      // for (int i = 0; i < 5; i++) {
      //   List<ConnectivityResult> connectionsResult =
      //   await (Connectivity().checkConnectivity());
      //   if (connectionsResult.contains(
      //     ConnectivityResult.mobile,
      //   ) ||
      //       connectionsResult.contains(ConnectivityResult.wifi)) {
      //     wifiPermissions = true;
      //     break;
      //   }
      //   await Future.delayed(const Duration(seconds: 1));
      // }

      // List<ConnectivityResult> connectionsResult =
      promiseArray
          .add((Connectivity().checkConnectivity()).then((connectionsResult) {
        if (connectionsResult.contains(
          ConnectivityResult.mobile,
        ) ||
            connectionsResult.contains(ConnectivityResult.wifi)) {
          wifiPermissions = true;
        }
        if (!wifiPermissions) {
          // 提示无网络权限
          return {
            "success": false,
            "wlqx": false,
            "msg": "暂无网络权限，请前往设置打开对应网络权限",
          } as Map<String, dynamic>;
        } else {
          return {
            "success": true,
            "wlqx": true,
          };
        }
      }));
      promiseArray.add(
          http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1')));
    }

    Future.wait(promiseArray).then((value) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          if (value.length > 2) {
            internetResponse = value[3];
          }else{
            internetResponse = {
              "success": true,
              "wlqx": true,
            };
          }
        });
        if (!internetResponse!["wlqx"]){
          WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
            if (mounted) {
              ToastUtil.show(context: context, msg: internetResponse!["msg"]);
            }
          });
        }

      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(360, 690),
      builder: (context, child) => MaterialApp(
        // navigatorObservers: [MyRouteObserver()],
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: [Locale('en', 'US'), Locale('zh', 'CN')],
        debugShowCheckedModeBanner: false,
        // title: 'Flutter Demo',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        ),
        routes: routes,
        navigatorObservers: [observer],
        // home: Scaffold(
        //   body: MyVideo(),
        // ),

        home: _isLoading
            ? Center(child: CircularProgressIndicator())
            : possibleAction(),
      ),
    );
  }

  Widget possibleAction() {

    // // 没有网络权限，进入首页
    if (internetResponse!["wlqx"]) {
      if (DeviceUtil.getDeviceKey() == null) {
        return const DeviceAskPage();
        // return const Text("data1");
      } else {
        // 登录
        if (getToken() == null) {
          // return const Text("data2");
          return const Automatic2Page();
        }
      }
    }
    // 这里以TabNavigator作为首页
    // 必须选中某考试才行
    if(IndustryDao.isInitExamKey()){
      return TabNavigator();
    }
    else{
      return SelectExamPage();
    }


  }
// _initFluwx() async {
//   await fluwx.registerApi(
//     appId: 'wxd930ea5d5a258f4f',
//     doOnAndroid: true,
//     doOnIOS: true,
//     universalLink: 'https://your.univerallink.com/link/',
//   );
//   var result = await fluwx.isWeChatInstalled;
//   debugPrint('is installed $result');
// }
}
